<?php

/**
 * This is the model class for table "user".
 *
 * The followings are the available columns in table 'user':
 * @property string $id
 * @property string $email
 * @property string $password
 * @property string $phone
 * @property string $first_name
 * @property string $last_name
 * @property string $city
 * @property string $role
 * @property integer $is_checked
 * @property string $check_code
 * @property integer $is_subscribed
 * @property integer $pockets
 * @property integer $referal_owner_id
 * @property string $created_at
 * @property string $ipaddress
 * @property string $cookie_id
 * @property double $balance
 * @property string $personal_key
 */
class User extends CActiveRecord
{
	public $_password2; 
	
	/**
	 * Returns the static model of the specified AR class.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'user';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			// registration
			array('email, password, _password2, first_name, last_name', 'required', 'on'=>'registration'),
			array('password', 'compare', 'compareAttribute'=>'_password2', 'on'=>'registration'),
			array('email', 'email', 'on'=>'registration'),
			array('email', 'unique', 'on'=>'registration'),
			// admin
			array('email, password, _password2, first_name, last_name', 'required', 'on'=>'admin'),
			array('password', 'compare', 'compareAttribute'=>'_password2', 'on'=>'admin'),
			array('email', 'email', 'on'=>'admin'),
			array('email', 'unique', 'on'=>'admin'),
			
			// profile
			array('first_name, last_name', 'required', 'on'=>'profile'),
			array('password', 'compare', 'compareAttribute'=>'_password2', 'on'=>'profile'),
//			array('email', 'email', 'on'=>'profile'),
//			array('email', 'unique', 'on'=>'profile'),
			
			// general
			array('is_checked, is_subscribed, pockets, referal_owner_id', 'numerical', 'integerOnly'=>true),
			array('balance', 'numerical'),
			array('email, password, first_name, last_name, city, check_code', 'length', 'max'=>255),
			array('phone', 'length', 'max'=>11),
			array('ipaddress', 'length', 'max'=>16),
			array('cookie_id, personal_key', 'length', 'max'=>40),
			array('role, education, sex, birthday', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, email, password, phone, first_name, last_name, city, role, is_checked, check_code, is_subscribed, pockets, referal_owner_id, created_at, ipaddress, cookie_id, balance, personal_key', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'email' => 'Email',
			'password' => 'Пароль',
			'_password2' => 'Подтверждение',
			'phone' => 'Тел.',
			'first_name' => 'Имя',
			'last_name' => 'Фамилия',
			'city' => 'Город',
			'role' => 'Role',
			'is_checked' => 'Is Checked',
			'check_code' => 'Check Code',
			'is_subscribed' => 'Is Subscribed',
			'pockets' => 'Pockets',
			'referal_owner_id' => 'Referal Owner',
			'created_at' => 'Created At',
			'ipaddress' => 'Ipaddress',
			'cookie_id' => 'Cookie',
			'balance' => 'Balance',
			'personal_key' => 'Personal Key',
			'education' =>'Образование',
			'sex'=>'Пол',
			'birthday'=>'Год рождения',
			'personal_link'=>'Ваша персональная ссылка:',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('phone',$this->phone,true);
		$criteria->compare('first_name',$this->first_name,true);
		$criteria->compare('last_name',$this->last_name,true);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('role',$this->role,true);
		$criteria->compare('is_checked',$this->is_checked);
		$criteria->compare('check_code',$this->check_code,true);
		$criteria->compare('is_subscribed',$this->is_subscribed);
		$criteria->compare('pockets',$this->pockets);
		$criteria->compare('referal_owner_id',$this->referal_owner_id);
		$criteria->compare('created_at',$this->created_at,true);
		$criteria->compare('ipaddress',$this->ipaddress,true);
		$criteria->compare('cookie_id',$this->cookie_id,true);
		$criteria->compare('balance',$this->balance);
		$criteria->compare('personal_key',$this->personal_key,true);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	
	
	/**
	 * 
	 */
	public static function getEductionData() {
		return Yii::app()->params['eduction'];	
	}
	
	/**
	 * 
	 */
	public static function getSexData() {
		return Yii::app()->params['sex'];	
	}
	
	/**
	 * 
	 */
	public static function getBirthdayData() {
		$currentYear = date('Y');
		$y = $currentYear - 100;
		$arr = array();
		
		for($i=$currentYear; $i>=$y; $i--) {
			$arr[$i] = $i;	
		}
		
		return $arr;	
	}
	
	/**
	 * 
	 */
	public static function getRoles() {
		return array('on_confirm'=>'On confirm', 'user'=>'User', 'admin'=>'Admin');	
	}
	
	/**
	 * 
	 */
	public static function getAllUser() {
		$criteria = new CDbCriteria;
		$criteria->order = '`email` ASC, `id` ASC';
		
		return User::model()->findAll($criteria);	
	}

	/**
	 * Get user model by email
	 * @param unknown_type $email
	 * @return User model
	 */
	public static function getByEmail($email) {
		return User::model()->findByAttributes(array('email'=>$email));	
	}
	
	/**
	 * Get user model by confirmatiom link
	 * @param unknown_type $cl
	 * @return User model
	 */
	public static function getByConfirmLink($cl) {
		return User::model()->findByAttributes(array('check_code'=>$cl));	
	}
	
	/**
	 * Get user model by personal key
	 * @param unknown_type $cl
	 * @return User model
	 */
	public static function getByPersonalKey($pk) {
		return User::model()->findByAttributes(array('personal_key'=>$pk));	
	}
	
	
	/**
	 * @return array, {code}=>value
	 */
	public function getCodeValueArray() {
		$arr = array();
		$arr['{email}'] = $this->email;
		$arr['{first_name}'] = $this->first_name;
		$arr['{last_name}'] = $this->last_name;
		$arr['{phone}'] = $this->phone;
		$arr['{city}'] = $this->city;
		$arr['{confirm_link}'] = $this->getConfirmLink();
		$arr['{personal_link}'] = $this->getPersonalLink();
		$arr['{mailer_link}'] = $this->getMailerLink();
		$arr['(profille_link)'] = Yii::app()->request->getBaseUrl(true) . '/user/profile/';
			
		return $arr;
	}
	
	/**
	 * @return confirmtion link
	 */
	public function getConfirmLink() {
		if(!$this->check_code)
			$this->createCheckCode();
		
		return Yii::app()->request->getBaseUrl(true) . '/user/cofirmation?cl='. $this->check_code;
	}
	
	
	/**
	 * @return personal link
	 */
	public function getPersonalLink() {
		if(!$this->personal_key)
			$this->createPersonalLink();
		
		return Yii::app()->request->getBaseUrl(true) . '/user/pl?pk='. $this->personal_key;
	}
	
	/**
	 * @return personal link
	 */
	public function getMailerLink() {
		if(!$this->personal_key)
			$this->createPersonalLink();
		
		return Yii::app()->request->getBaseUrl(true) . '/user/mlr?pk='. $this->personal_key;
	}
	
	/**
	 * @return personal link
	 */
	public function getFakeLink() {
		if(!$this->personal_key)
			$this->createPersonalLink();
		
		return Yii::app()->request->getBaseUrl(true) . '/user/fk?pk='. $this->personal_key;
	}
	
	public function getChildrensCount($start = false, $end = false) {
		$criteria = new CDbCriteria;
		$criteria->condition = '`referal_owner_id`='. $this->id;
		if($start || $end)
			$criteria->addBetweenCondition('created_at', $start, $end);
		
		return User::model()->count($criteria);		
	}
	
	/**
	 * Get Admin model
	 */
	public function getAdmin() {
		$criteria = new CDbCriteria;
		$criteria->condition = '`role`= "admin"';
		
		return User::model()->find($criteria);		
	}
	
	
	/**
	 * Login user
	 */
	public function login(){
		// logout if user authorized(for chenged role)
		if(!Yii::app()->user->getIsGuest())
			Yii::app()->user->logout();
		
		$identity = new UserIdentity($this->email,$this->password);
		$identity->updateRoles($this);
		
		Yii::app()->user->login($identity, 3600*24*30);
	}
	
	/**
	 * 
	 */
	public function createCheckCode() {
		$this->check_code = preg_replace("/[^0-9]/", '', md5($this->id));
		$this->save(false);
	}
	
	/**
	 * 
	 */
	public function createPersonalLink() {
		$first_name = Functions::encodestring($this->first_name);
		$last_name = Functions::encodestring($this->last_name);
		$i = substr(preg_replace("/[^0-9]/", '', md5($this->id)), 0, 10);
		$this->personal_key = $first_name .'-'. $last_name .'-'. $i;
		$this->save(false);
	}
	
	/**
	 * Generate password
	 */
	public static function generatePass() {
		return substr(md5(time()), 0, 6);
	}
	
	/**
	 *  After registration send to user email with confirmation link
	 */
	public function sendConfirmation() {
		$mailData = MailTemplates::getTemplateByAlias('email_confirmation', $this->getCodeValueArray());
		// save email in db
		
		Mail::saveEmail($this->email, $mailData);
	}
	
	/**
	 * create saev send new password
	 */
	public function sendNewPas() {
		// get array with values
		$arr = $this->getCodeValueArray();
		$arr['{new_password}'] = User::generatePass();
		
		//save new pass
		$this->password = md5($arr['{new_password}']);
		$this->save(false);
		
		//send email
		$mailData = MailTemplates::getTemplateByAlias('new_password', $arr);
		Mail::saveEmail($this->email, $mailData);
		
	}
	
	public static function sendToAdmin($templateAlias) {
		$admin = User::getAdmin();
		
		$mailData = MailTemplates::getTemplateByAlias($templateAlias);
		Mail::saveEmail($admin->email, $mailData);
	}
	
	/**
	 *  send email to a friend
	 * @param email
	 */
	public function sendToFriend($email, $first_name, $last_name) {
		$statId = $this->saveMailerStatistic($email, $first_name, $last_name);
		
		$arr['{send_to_name}'] = $first_name .' '. $last_name;
		$arr['{sender_name}'] = $this->first_name .' '. $this->last_name;
		$arr['{mailer_link}'] =  $this->getMailerLink() .'_'. $statId;
		$arr['{fake_link}'] =  $this->getFakeLink();

		$mailData = MailTemplates::getTemplateByAlias('send_to_friend', $arr);
		$mailData['subject'] = Functions::str_replace_assoc($arr, $mailData['subject']);
		Mail::saveEmail($email, $mailData);
	}
	
	/**
	 * check to owner
	 */
	public function checkToOwner() {
		if(isset(Yii::app()->request->cookies['pk']->value)) {
			$user = User::getByPersonalKey(Yii::app()->request->cookies['pk']->value);
			if($user) {
				$this->referal_owner_id = $user->id;
				$this->save(false);
				// add points for owner
				$user->updateBalance((int)Configuration::getValue('point_for_owner'));
			}
			
			unset(Yii::app()->request->cookies['pk']);
		}

		if(isset(Yii::app()->request->cookies['mlr']->value)) {
			$user = User::getByPersonalKey(Yii::app()->request->cookies['mlr']->value);
			if($user) {
				$this->referal_owner_id = $user->id;
				$this->save(false);
				// add points for owner
				$user->updateBalance(1);
			}
			
			unset(Yii::app()->request->cookies['mlr']);
		} 
	}

	/**
	 *  update balance static method
	 * @param user_id (int)
	 * @param balance (float)
	 */
	public static function updateBalanceById($id, $balance) {
		if($user = User::model()->findByPk($id)) {
			return $user->updateBalance($balance);
		} else {
			return false;
		}	
	}
	
	/**
	 *  update balance 
	 * @param balance (float)
	 */
	public function updateBalance($balance) {
		$this->balance = $this->balance + $balance;
		if($this->save(false))
			return true;
		else 
			return false;
	}
	
	/**
	 *  update complaint 
	 * @param complaint 
	 */
	public function updateComplaint($complaint) {
		$this->complaint = $this->complaint + $complaint;
		if($this->save(false))
			return true;
		else 
			return false;
	}
	
	/**
	 * Save meailer statistic 
	 */
	public function saveMailerStatistic($email, $first_name, $last_name) {
		$obj = new UserMailerStatistic;
		$obj->user_id = $this->id;
		$obj->email = $email;
		$obj->first_name = $first_name;
		$obj->last_name = $last_name;
		$obj->save(false);
		
		return $obj->id;
	}
	
	/**
	 * @param month count $period
	 */
	public function getPLStatistic($start = false, $end = false) {
		if($start || $end) {
			$start == '' ? $start = '1970-01-01' : '';
			$end == '' ? $end = date('Y-m-d') : '';
		}
		
		$arr['entered'] = UserPLStatistic::getStatictis($this->id, $start, $end);
		if($arr['entered'] != 0) { 
			$arr['registered'] = $this->getChildrensCount($start, $end); 
			$arr['points'] = $arr['registered'] * Configuration::getValue('point_for_owner');
		} else
			return false;
			
		return $arr;
	}
	
	/**
	 * parse personal link get personal key and id in user_mailer_statistic
	 * @return array('id'=>.., 'pk'=>..)
	 */
	public static function parsePersonalLink($str) {
		$p = strpos($str, '_');		
		$arr['id'] = substr($str, $p+1);
		$arr['pk'] = substr($str, 0, $p);
		
		return $arr;
	}
}